package cn.e4j.modular.api.controller;

import cn.digiwin.wx.utils.WeixinHandler;
import cn.digiwin.wx.utils.WordToPinYinUtil;
import cn.e4j.core.dto.Dtos;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.reqres.response.ErrorResponseData;
import cn.e4j.core.reqres.response.ResponseData;
import cn.e4j.core.util.DateUtils;
import cn.e4j.core.util.ToolUtil;
import cn.e4j.modular.api.service.GwaService;
import cn.e4j.modular.api.service.WXUserService;
import cn.e4j.modular.api.util.ControllerSupport;
import cn.e4j.modular.crm.entity.GwaaT;
import cn.e4j.modular.crm.mapper.GwaaTMapper;
import cn.e4j.modular.system.entity.SysUser;
import cn.e4j.modular.system.entity.SysUserRole;
import cn.e4j.modular.system.mapper.SysRoleModuleMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *功能描述
 * @author caijy
 * @description
 * @datetime 2019-10-8 0008 12:06
 * @return
 */
@RestController
@RequestMapping("/api/wx/user/")
public class UserApiController extends ControllerSupport {

    @Autowired
    WXUserService wxUserService;

    @Autowired
    private GwaaTMapper gwaaTMapper;

    @Autowired
    private SysRoleModuleMapper sysRoleModuleMapper;

    @Autowired
    private WXUserService userService;

    @Autowired
    GwaService gwaService;

    /**
     * 获取微信用户信息+权限
     */
    @RequestMapping(value = "infos", method = RequestMethod.POST)
    public ResponseData infos(@DtoParam DtoWapper dtoWapper) {
        Dto dto = dtoWapper.getDto();
        SysUser user = dtoWapper.getSysUser();
        Map<String, Object> out = new HashedMap();
        List<Dto> list = new ArrayList<>();
//        dto.put("CASCADE_ID","0.003.004");
//        dto.put("ICON_NAME","icon-27");
//        dto.put("IS_LEAF","1");
//        dto.put("NAME","注册");
//        dto.put("SORT_NO",1);
//        dto.put("URL","register/register");
//        list.add(dto);
        try {
            dto.put("GWAA001", user.getACCOUNT());
            dto.put("GWAAACTI", "Y");
            dto.put("GWAAENT", user.getDBC());
            dto.put("USER_ID", user.getID());
            dto.put("CASCADE_ID", "0.003.");//微信模块
            out.put("user", gwaaTMapper.getGwaaUser(dto));
            out.put("auths", sysRoleModuleMapper.selectModulesOfWXUser(dto));
//            out.put("auths", list);
            out.put("sysUser", user);

        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
        return SUCCESS(out);
    }


    /**
     * 获取用户列表数据
     *
     * @return
     */
    @RequestMapping(value = "getUserList")
    public ResponseData getUserList(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        List<Dto> list = new ArrayList<>();
        try {
            inDto.put("GWAAENT", inDto.getString("ENT"));
            inDto.put("GWAAACTI", inDto.getString("status"));
            list = userService.getUserList(wapper.getPage(),inDto);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ERROR;
        }
        return SUCCESS(list);
    }

    /**
     * 用户注册
     */
    @RequestMapping(value = "registerUser", method = RequestMethod.POST)
    public ResponseData registerUser(@DtoParam DtoWapper wapper) {

        Dto inDto = wapper.getDto();
        Dto outDto = new Dto();
        String gwaa001 =null;
        String gwaa004 =null;
        try {
            //匹配 微信账号是否在 后台已经提交注册了
            Dto param = new Dto();
            if(inDto.getString("source").equals("G")){
                param.put("GWAA003",inDto.getString("GWAA001"));
//                param.put("source",inDto.getString("source"));//公众号
            }else {
                param.put("GWAA001",inDto.getString("GWAA001"));
//                param.put("source","Q");//公众号
            }
//            param.put("GWAA001", inDto.getString("GWAA001"));
            param.put("GWAAACTI", "N");
            GwaaT user = wxUserService.getUserData(param);
            if (ToolUtil.isNotEmpty(user)) {
                return new ErrorResponseData(600,"用户已申请绑定，请等待管理员审核");
            }

            //判断是否是已审核用户
            param.put("GWAAACTI", "Y");
            user = wxUserService.getUserData(param);
            if (ToolUtil.isNotEmpty(user)) {
                return new ErrorResponseData(601,"用户已审核，不需要进行注册");
            }

            if(inDto.getString("source").equals("G")){
                //根据gwaa002转换成拼音时校验账号是否存在
                gwaa001 = WordToPinYinUtil.ToFirstCharUpperCase(inDto.getString("GWAA002"));
                gwaa004 = inDto.getString("GWAA004");
                gwaa001 = gwaa001 + gwaa004.substring(gwaa004.length()-4,gwaa004.length());
                param.put("GWAA001",gwaa001);
                param.put("GWAAACTI", "N");
                user = wxUserService.getUserData(param);
                if (ToolUtil.isNotEmpty(user)) {
                    return new ErrorResponseData(600,"用户已申请绑定，请等待管理员审核");
                }

                //判断是否是已审核用户
                param.put("GWAAACTI", "Y");
                user = wxUserService.getUserData(param);
                if (ToolUtil.isNotEmpty(user)) {
                    return new ErrorResponseData(601,"用户已审核，不需要进行注册");
                }
            }
            param.put("GWAAACTI_Old", "T");
            param.put("GWAAACTI", "N");//新增 未审核
//            param.put("gwaatime", DateUtils.getTime());//资料时间
//            param.put("gwaadate", AppUtils.getDateTime());//资料建立日期
            param.put("GWAAENT", inDto.getString("ENT"));
            param.put("GWAA001_NEW", gwaa001);
            param.put("GWAA001", inDto.getString("GWAA001"));
            param.put("GWAA002", inDto.getString("GWAA002"));
            param.put("GWAA004", inDto.getString("GWAA004"));
            param.put("GWAA005", inDto.getString("GWAA005"));
            param.put("GWAA006", inDto.getString("GWAA006"));
            param.put("GWAA007", inDto.getString("GWAA007"));
            param.put("GWAA008", inDto.getString("GWAA008"));

            // 外部用户
            if (param.getString("GWAA007").equals("1")) {
                param.put("GWAA009", inDto.getString("GWAK001"));//交易对象编号
                param.put("GWAA011", inDto.getString("email"));
                param.put("GWAA013", inDto.getString("address"));
                param.put("GWAA017", inDto.getString("GWAA017"));
                param.put("GWAA018", inDto.getString("GWAA018"));
                param.put("GWAA022", inDto.getString("GWAA022"));
            }

//            param.put("GWAAMODU",inDto.getString("GWAA001"));

            //只更新gwaa sysuser的ORGID审核后才能被赋值
            wxUserService.updateByKeyActi(param);

            //查询具有注册审核权限的用户的微信号
            Dto roleDto = Dtos.newDto();
            //roleDto.put("role_id_", "18052315553200117");//管理员
            //List<Dto> sysUser = systemService.getUserByRoleId(roleDto);
            List<Dto> sysUser = wxUserService.getGwaaByZcsh(roleDto);

            //通知所有管理员
            WeixinHandler.sendMsg(sysUser, "有新人员[" +
                    inDto.getString("GWAA002") + "," +
                    inDto.getString("GWAA004") + "]注册，请到销售服务审核！");

            outDto.setAppMsg("申请提交成功。\n请等待平台管理员审核！");
            outDto.put("data", inDto);

        } catch (Exception ex) {
            ex.printStackTrace();
            return ERROR("注册异常！");
        }

        return SUCCESS(outDto);
    }


    /**
     * 审核
     *
     * @return
     */
    @RequestMapping(value = "checkUserData")
    public ResponseData checkUserData(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        SysUser currentUser = wapper.getSysUser();
        try {

            //匹配 微信账号是否在 后台是否已经审核
            Dto param = new Dto();
            param.put("GWAA001", inDto.getString("GWAA001"));
            param.put("GWAAACTI", "Y");
            GwaaT user = wxUserService.getUserData(param);
            if (ToolUtil.isNotEmpty(user)) {
                return ERROR(600,"此用户已被审核过了!");
            } else {
                SysUser regUser = new SysUser().selectOne(new QueryWrapper<SysUser>().eq("ACCOUNT", inDto.getString("GWAA001")));
                SysUser sysUser = new SysUser();
                sysUser.setID(regUser!=null?regUser.getID():" ");
                sysUser.setORG_ID(inDto.getString("GWAA008"));
                sysUser.setTYPE(inDto.getString("GWAA007"));
                sysUser.setDBC(inDto.getString("ENT"));
                //sysUser.setName_(userName);
                //sysUser.setMobile_(mobile);
                param.put("GWAAACTI_Old", "N");
                param.put("GWAAACTI", "Y");
                param.put("GWAA007", inDto.getString("GWAA007"));
                param.put("GWAA008", inDto.getString("GWAA008"));
                param.put("GWAAENT", inDto.getString("ENT"));
                param.put("GWAAMODU", currentUser.getID());
                if (param.getString("GWAA007").equals("1")) {

                    param.put("GWAA009", inDto.getString("GWAA009"));//交易对象编号
                    param.put("GWAA011", inDto.getString("GWAA011"));
                    param.put("GWAA013", inDto.getString("GWAA013"));
                    param.put("GWAA017", inDto.getString("GWAA017"));
                    param.put("GWAA018", inDto.getString("GWAA018"));

                    sysUser.setEMAIL(param.getString("GWAA011"));
                    sysUser.setADDRESS(param.getString("GWAA13"));
                }
                SysUserRole sys_user_rolePO = new SysUserRole();
                sys_user_rolePO.setID(DateUtils.getDate("yyyyMMddHHmmssSSS"));
                sys_user_rolePO.setCREATE_TIME(LocalDateTime.now());
                sys_user_rolePO.setCREATE_BY(currentUser.getID());
                sys_user_rolePO.setROLE_ID(inDto.getString("ROLE_ID"));

                sys_user_rolePO.setUSER_ID(regUser!=null?regUser.getID():" ");

                wxUserService.checkUserSave(param, sysUser, sys_user_rolePO);

                WeixinHandler.sendMsg(param,
                        String.format("恭喜您的申请已经审核通过！审核员[%s],审核时间[%s]",
                                currentUser.getNAME(),
                                DateUtils.getDate(DateUtils.PATTERN_yyyy_MM_dd_HH_mm_ss)));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ERROR("审核异常!");
        }

        return SUCCESS;
    }

    @RequestMapping(value = "getGwadDatas")
    public ResponseData getGwadDatas(@DtoParam DtoWapper wapper) {
        Dto inDto =wapper.getDto();
        inDto.put("LANG", "2");
        List<Dto> list = gwaService.getGwad(inDto);
        return SUCCESS(list);
    }

    //客户行业 一级分类
    @RequestMapping(value = "getGwbwDatas")
    public ResponseData getGwbwDatas(@DtoParam DtoWapper wapper) {
        Dto inDto =wapper.getDto();
        inDto.put("LANG", "2");
        return SUCCESS(gwaService.getGwbw(inDto));
    }

    //客户行业 二级分类
    @RequestMapping(value = "getGwagDatas")
    public ResponseData getGwagDatas(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        inDto.put("LANG", "2");
        return SUCCESS(gwaService.getGwag(inDto));
    }


    @RequestMapping(value = "getPlantDatas")
    public ResponseData getPlantDatas(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        List<Dto> list = new ArrayList<>();
        try {
            list = gwaService.getOrg(inDto);
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
        return SUCCESS(list);
    }

    //客户名称
    @RequestMapping(value = "getGwakDatas")
    public ResponseData getGwakDatas(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        List<Dto> list = new ArrayList<>();
        inDto.put("LANG", "2");
        try {
            list = gwaService.getGwak(inDto);
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
        return SUCCESS(list);
    }

    @ResponseBody
    @RequestMapping(value = "getProvinces")
    public ResponseData getProvinces(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        inDto.put("LANG", "2");
        return SUCCESS(gwaService.getProvinces(inDto));
    }

    @ResponseBody
    @RequestMapping(value = "getCitys")
    public ResponseData getCitys(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        inDto.put("LANG", "2");
        List<Dto> list = gwaService.getCitys(inDto);
        return SUCCESS(list);
    }

    @ResponseBody
    @RequestMapping(value = "getDistricts")
    public ResponseData getDistricts(@DtoParam DtoWapper wapper) {
        Dto inDto = wapper.getDto();
        inDto.put("LANG", "2");
        List<Dto> list = gwaService.getDistricts(inDto);
        return SUCCESS(list);
    }
}
